package top.infopub.mgr.sts.web;


import com.github.pagehelper.Page;
import com.google.common.collect.Maps;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.generic.GenericController;
import top.infopub.mgr.bpa.domain.ProContractDomain;
import top.infopub.mgr.bpa.service.*;
import top.infopub.mgr.cap.service.LoanFinDetailService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.sts.domain.QaCapDetailDomain;
import top.infopub.mgr.sts.domain.QaConsoleDomain;
import top.infopub.mgr.sts.service.*;
import top.infopub.model.bpa.EffectSure;
import top.infopub.model.bpa.ProContractUla;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.sts.*;
import top.infopub.security.util.SessionUserUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


/**
 * 经营质量分析报表
 * @author Awoke
 * @version 2020年1月18日
 * @see QaConsoleController
 * @since
 */
@Controller
@RequestMapping("/qaConsole")
public class QaConsoleController extends GenericController {

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private OrgSuperQaService orgSuperQaService;

    @Autowired
    private OrgAreaQaService orgAreaQaService;

    @Autowired
    private OrgProQaService orgProQaService;
    
    @Autowired
    private ProSelfCaeService proSelfCaeService;
    
    @Autowired
    private ProInvestPoolService proInvestPoolService;
    
    @Autowired
    private ProProfitPoolService proProfitPoolService;
    
    @Autowired
    private ProCashinPoolService proCashinPoolService;
    
    @Autowired
    private ProCashoutPoolService proCashoutPoolService;
    
    @Autowired
    private ProContractService proContractService;
    
    @Autowired
    private ContractExtService contractExtService;
    
    @Autowired
    private ContractExtInvestService contractExtInvstService;
    
    @Autowired
    private ProContractUlaService proContractUlaService;
    
    @Autowired
    private EffectSureService effectSureService;
    
    @Autowired
    private LoanFinDetailService loanFinDetailService;

    /**
     * 列表页
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            Map<String, Object> where = Maps.newHashMap();
            where.put("state", "1");
            where.put("orderCondition", " types asc ");
            orgInfos = orgInfoService.selectByMapWhere(where);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "sts/lay-qaConsole-list";
    }

    /**
     * 根据条件获取获取列表数据
     * @param stsMonth
     * @param orgTypeAndId ${org.id}-${org.types}
     * @param paramPage
     * @return 
     * @throws ParseException 
     * @see
     */
    @RequestMapping("/queryDataByCondition")
    public @ResponseBody RspVo<QaConsoleDomain> queryDataByCondition(String stsMonth,
                                                                     String orgTypeAndId)
        throws ParseException {
        if (StringUtils.isBlank(stsMonth)) {
            return RspVo.getFailureResponse(-1, "请选择统计月份~");
        }
        if (StringUtils.isBlank(orgTypeAndId)) {
            return RspVo.getFailureResponse(-1, "请选择公司主体~");
        }
        List<QaConsoleDomain> result = Lists.newArrayList();
        Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
        String orgId = orgTypeAndId.split("-")[0];
        String type = orgTypeAndId.split("-")[1];
        if ("1".equals(type)) {//公司主体为总部公司
            result = orgSuperQaService.selectQaConsoleByWhere(month, orgId);
        }else if ("2".equals(type)) {//公司主体为区域公司
            result = orgAreaQaService.selectQaAreaByWhere(month, orgId);
        }else if ("3".equals(type)) {//公司主体为项目公司
            result = orgProQaService.selectQaProByWhere(month, orgId);
        }
        return RspVo.getSuccessResponse(0, result);
    }
    
    /**
     * 根据条件公司指标完成率
     * @param stsMonth 年-月
     * @param orgTypeAndId 公司类型和公司id
     * @return
     */
    @RequestMapping("/getQaRateByMonthAndId")
    @ResponseBody
    public Map<String, Object> getQaRateByMonthAndId(String stsMonth, String orgTypeAndId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<QaConsoleDomain> result = Lists.newArrayList();
            Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
            String orgId = orgTypeAndId.split("-")[0];
            String type = orgTypeAndId.split("-")[1];
            if ("1".equals(type)) {//公司主体为总部公司
                result = orgSuperQaService.selectQaRateByWhere(month, orgId);
            }else if ("2".equals(type)) {//公司主体为区域公司
                result = orgAreaQaService.selectQaRateByWhere(month, orgId);
            }else if ("3".equals(type)) {//公司主体为项目公司
                result = orgProQaService.selectQaRateByWhere(month, orgId);
            }
            map.put("qaRates", result);
        } catch (Exception e) {
            log.error("查询公司指标完成率异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
    
    /**
     * 根据条件公司经营质量指标金额数据
     * @param year 年
     * @param orgTypeAndId 公司类型和公司id
     * @param aimType 指标类型
     * @return
     */
    @RequestMapping("/getQaAmountByYearAndId")
    @ResponseBody
    public Map<String, Object> getQaAmountByYearAndId(String year, String orgTypeAndId, String aimType) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<QaConsoleDomain> result = Lists.newArrayList();
            String orgId = orgTypeAndId.split("-")[0];
            String type = orgTypeAndId.split("-")[1];
            Integer belongsYear = Integer.parseInt(year);
            if ("1".equals(type)) {//公司主体为总部公司
                result = orgSuperQaService.selectQaAmountByWhere(belongsYear, orgId, aimType);
            }else if ("2".equals(type)) {//公司主体为区域公司
                result = orgAreaQaService.selectQaAmountByWhere(belongsYear, orgId, aimType);
            }else if ("3".equals(type)) {//公司主体为项目公司
                result = orgProQaService.selectQaAmountByWhere(belongsYear, orgId, aimType);
            }
            map.put("qaAmounts", result);
        } catch (Exception e) {
            log.error("查询公司指标金额数据异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
    
    /**
     * 自行承接建安额列表页
     * @return
     */
    @RequestMapping("/selfCaeList")
    public String selfCaeList(HttpServletRequest request) {
        request.setAttribute("orgId", request.getParameter("orgId"));
        request.setAttribute("orgType", request.getParameter("orgType"));
        request.setAttribute("stsMonth", request.getParameter("stsMonth"));
        request.setAttribute("orgName", request.getParameter("orgName"));
        if("1".equals(request.getParameter("orgType"))){
            return "sts/lay-qaSelfCaeArea-list";
        }else{
            return "sts/lay-qaSelfCaePro-list";
        }
    }

    /**
     * 根据条件获取区域公司自行承接建安额列表数据
     * @param stsMonth
     * @param orgId
     * @param paramPage
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryAreaSelfCaeByCondition")
    public @ResponseBody RspVo<QaConsoleDomain> queryAreaSelfCaeByCondition(String stsMonth, String orgId, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(stsMonth)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<QaConsoleDomain> page = new Page<QaConsoleDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
        page = orgAreaQaService.selectSelfCaeAreaByWhere(page, month, orgId);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取项目自行承接建安额列表数据
     * @param stsMonth
     * @param orgId
     * @param paramPage
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryProSelfCaeByCondition")
    public @ResponseBody RspVo<ProSelfCae> queryProSelfCaeByCondition(String stsMonth, String orgId, ParamPage paramPage)
            throws ParseException {
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(stsMonth)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
        Page<ProSelfCae> page = new Page<ProSelfCae>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proSelfCaeService.selectProSelfCaeByWhere(page, month, orgId);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 自行承接建安额列表页
     * @return
     */
    @RequestMapping("/targetList")
    public String targetList(HttpServletRequest request) {
        String orgType = request.getParameter("orgType");
        String aimType = request.getParameter("aimType");
        String targetName = request.getParameter("targetName");
        request.setAttribute("orgId", request.getParameter("orgId"));
        request.setAttribute("orgType", orgType);
        request.setAttribute("aimType", aimType);
        request.setAttribute("stsMonth", request.getParameter("stsMonth"));
        request.setAttribute("orgName", request.getParameter("orgName"));
        request.setAttribute("targetName", targetName);
        if("1".equals(request.getParameter("orgType"))){
            return "sts/lay-qaTargetArea-list";
        }else{
            return "sts/lay-qaTargetPro-list";
        }
    }
    
    /**
     * 根据条件获取区域公司经营指标列表数据
     * @param stsMonth
     * @param orgId
     * @param aimType
     * @param paramPage
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryAreaTargetByCondition")
    public @ResponseBody RspVo<QaConsoleDomain> queryAreaTargetByCondition(String stsMonth, String orgId, String aimType, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(stsMonth) || StringUtils.isBlank(aimType)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<QaConsoleDomain> page = new Page<QaConsoleDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
        page = orgAreaQaService.selectTargetAreaByWhere(page, month, orgId, aimType);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取项目经营指标列表数据
     * @param stsMonth
     * @param orgId
     * @param aimType
     * @param paramPage
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryProTargetByCondition")
    public @ResponseBody RspVo<QaConsoleDomain> queryProTargetByCondition(String stsMonth, String orgId, String aimType, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(stsMonth)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Date month = DateUtils.parseDate(stsMonth, "yyyy年MM月");
        Page<QaConsoleDomain> page = new Page<QaConsoleDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = orgProQaService.selectProTargetByWhere(page, month, orgId, aimType);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 项目信息详情页
     * @return
     */
    @RequestMapping("/qaProDetail")
    public String qaProDetail(HttpServletRequest request) {
        String proCode = request.getParameter("proCode");
        String aimType = request.getParameter("aimType");
        
        /**
         * 项目合同信息
         */
        ProContractDomain proContractDomain= proContractService.selectByContractProCode(proCode);
        request.setAttribute("proContract", proContractDomain);
        
//        /**
//         * 最新的承继协议信息
//         */
//        ContractExt contractExt = contractExtService.selectLatestContractExtByProCode(proCode);
//        request.setAttribute("contractExt", contractExt);
        
//        /**
//         * 最新承继协议合同投资信息
//         */
//        ContractExtInvest contractExtInvest = new ContractExtInvest();
//        if(contractExt != null){
//            contractExtInvest = contractExtInvstService.selectLatestContractExtInvestByExtId(contractExt.getId());
//        }
//        request.setAttribute("contractExtInvest", contractExtInvest);
        
        /**
         * 获取公式信息
         */
        if(proContractDomain != null){
            Map<String,Object> where = new HashMap<String, Object>();
            where.put("proContractId", proContractDomain.getId());
            where.put("orderCondition", "FORMULA_TYPE");
            List<ProContractUla> proContractUlas = proContractUlaService.selectByMapWhere(where);
            request.setAttribute("proContractUlas", proContractUlas);
        }
        
        /**
         * 最新的创效确认信息
         */
        EffectSure effectSure = effectSureService.selectLatestEffectSureByProCode(proCode);
        request.setAttribute("effectSure", effectSure);
        
        //融资总额（万元）
        BigDecimal capTotal = loanFinDetailService.selectTotalLoanAmount(proCode);
        //投资总额（万元）
        BigDecimal investTotal = proInvestPoolService.selectTotalInvestAmount(proCode);
        //管理净利润总额（万元）
        BigDecimal profitTotal = proProfitPoolService.selectTotalProfitAmount(proCode);
        //投资性现金流入（万元）
        BigDecimal cashinTotal = proCashinPoolService.selectTotalCashinAmount(proCode);
        //投资性现金流出（万元）
        BigDecimal cashoutTotal = proCashoutPoolService.selectTotalCashoutAmount(proCode);
        
        request.setAttribute("proCode", proCode);
        request.setAttribute("aimType", aimType);
        request.setAttribute("capTotal", capTotal);
        request.setAttribute("investTotal", investTotal);
        request.setAttribute("profitTotal", profitTotal);
        request.setAttribute("cashinTotal", cashinTotal);
        request.setAttribute("cashoutTotal", cashoutTotal);
        return "sts/lay-qaProDetail-list";
    }
    
    /**
     * 根据条件获取融资额列表数据
     * @param proCode
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryCapDataByCondition")
    public @ResponseBody RspVo<QaCapDetailDomain> queryCapDataByCondition(String proCode, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(proCode)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<QaCapDetailDomain> page = new Page<QaCapDetailDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = loanFinDetailService.selectQaDataByWhere(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取投资额列表数据
     * @param proCode
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryInvestDataByCondition")
    public @ResponseBody RspVo<ProInvestPool> queryInvestDataByCondition(String proCode, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(proCode)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<ProInvestPool> page = new Page<ProInvestPool>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proInvestPoolService.selectQaDataByWhere(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取管理净利润列表数据
     * @param proCode
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryProfitDataByCondition")
    public @ResponseBody RspVo<ProProfitPool> queryProfitDataByCondition(String proCode, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(proCode)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<ProProfitPool> page = new Page<ProProfitPool>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proProfitPoolService.selectQaDataByWhere(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取投资性现金流入列表数据
     * @param proCode
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryCashinDataByCondition")
    public @ResponseBody RspVo<ProCashinPool> queryCashinDataByCondition(String proCode, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(proCode)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<ProCashinPool> page = new Page<ProCashinPool>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proCashinPoolService.selectQaDataByWhere(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 根据条件获取投资性现金流出列表数据
     * @param proCode
     * @return 
     * @throws ParseException 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryCashoutDataByCondition")
    public @ResponseBody RspVo<ProCashoutPool> queryCashoutDataByCondition(String proCode, ParamPage paramPage)
        throws ParseException {
        if (StringUtils.isBlank(proCode)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        Page<ProCashoutPool> page = new Page<ProCashoutPool>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proCashoutPoolService.selectQaDataByWhere(page, proCode);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
}
